/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: dings
 * Date: 2024-07-09
 * Time: 16:22
 */

  class ListNode {
     int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
     }
 }
 class Solution {
     public ListNode detectCycle(ListNode head) {
         //head为空时
         if (head == null) {
             return head;
         }

         ListNode fast = head;
         ListNode slow = head;

         //确定相遇时的节点
         while (fast != null && fast.next != null) {
             fast = fast.next.next;
             slow = slow.next;
             if (fast == slow) {
                 break;
             }
         }
         //不是环
         if (fast == null || fast.next == null) {
             return null;
         }
         //从起点和相遇节点开始相向而行，相遇的节点就是入口点
         ListNode curH = head;
         while (curH != slow) {
             curH = curH.next;
             slow = slow.next;
         }
         return slow;
     }
}
public class Test {
}